package com.cnzha.zk;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 服务
 *
 * @Author: zhaoxin
 * @email: zdkk@foxmail.com
 * @Date: 2020/4/7 23:20
 */
public class DistributeServer {


    public static final String clust = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    public static final int sessionTimeOut = 2000;
    private String parentNode = "/servers";
    private ZooKeeper zooKeeper;

    public void init() throws IOException {

        zooKeeper = new ZooKeeper(clust, sessionTimeOut, (watchedEvent) -> {
            //process回调
            Watcher.Event.EventType type = watchedEvent.getType();
            String path = watchedEvent.getPath();
            System.out.println("path = " + path);
            System.out.println("type = " + type);
            //再次启动监听
            try {
                zooKeeper.getChildren("/", true);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    public void registServer(String hostName) throws KeeperException, InterruptedException {
        String s = zooKeeper.create(parentNode + "/" + hostName, hostName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("registe success = " + s);
    }

    public void bussiness(String hostName) throws InterruptedException {
        System.out.println(hostName + " Working ...");
        TimeUnit.MILLISECONDS.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        DistributeServer distributeServer = new DistributeServer();
        distributeServer.init();
        distributeServer.registServer(args[0]);
        distributeServer.bussiness(args[0]);
    }

}
